package com.usyk;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: oleksii.usyk@gmail.com
 * Date: 04.01.12
 * Time: 20:44
 */
public class RatingParser {

    public static Map<Level, Double> parse(String filePath, List<String> nextLevelNames) throws IOException {
        return parse(new File(filePath), nextLevelNames);
    }

    /**
     * Returns Map from parsed levels (just with name) into Rating of this level
     *
     * @param file
     * @param nextLevelNames
     * @return
     * @throws IOException
     */
    public static Map<Level, Double> parse(File file, List<String> nextLevelNames) throws IOException {

        List<String> lines = FileUtils.readLines(file);
        Map<Level, Double> result = new HashMap<Level, Double>(lines.size());
        for (String line : lines) {
            String[] columns = line.split(",");
            if (columns.length != 2) {
                throw new IllegalArgumentException("There are " + columns.length +
                        " columns in file " + file.getAbsolutePath() + " but should be only 2");
            }
            String levelName = columns[0];
         //   if (nextLevelNames.contains(levelName)) {
                Level level = new Level();
                level.setName(levelName);
                result.put(level, Double.valueOf(columns[1]));
         //   } else {
         //       throw new IllegalArgumentException("Invalid column name in file " + file.getAbsolutePath() +
          //              " : expected one of the next '" + nextLevelNames + "' but was " + levelName);
          //  }

        }

        validateSum(result.values(),file.getAbsolutePath());

        return result;
    }

    private static void validateSum(Collection<Double> values, String levelName) {
        Double sum = 0d;
        for (Double d : values) {
            sum += d;
        }
        if (!(Math.abs(sum - 1d) <= 0.0000001)) {
           throw new IllegalStateException("Sum of " + levelName + " was " + sum + " but should be 1");
        }
    }

}
